<template>
  <div style="width: 100%;height: 100%;display: flex;">
    <div style="width:9%;min-height: 100px;position: absolute;z-index:10;top: 30px;left: 30px ">
      <el-tree
          style="background-color:rgba(64, 158, 255,0.88);color: #eeeeee;border-radius: 20px;padding: 5px"
          :data="dataTree"
          ref="treeRef"
          highlight-current
          accordion
          :render-content="renderContent"
          :props="defaultProps"
          default-expand-all
          node-key="id"
          @node-click="handleNodeClick"
      ></el-tree>
    </div>
    <div id="container" style="width:100%; height: 100%;"></div>

    <el-dialog :visible.sync="showDialog" title="门店信息" width="40%">
      <div>门店名称：{{ storeInfo.name }}</div>
      <div>
        摄像头列表：
        <el-link
            v-for="(item, index) in formatSerialNumber(storeInfo.serialNumber)"
            :key="index"
            style="color: #66b1ff; text-decoration: underline;margin-right: 10px"
            @click="_open(item)"
        >
          {{ item }}
        </el-link>
      </div>
    </el-dialog>

    <open-cctv ref="cctv"></open-cctv>
  </div>
</template>

<script>
// import box from './components/videoControl.vue';
import openCctv from "./componentDialog/openCctv.vue";

export default {
  name: "earth",
  meta: { title: "视频地图", icon: "el-icon-basketball", authorityList: 300, sort: 1 },
  components: { openCctv },
  data() {
    return {
      map: null,
      open: false,
      dataTree: [
        {
          label: "品牌方列表",
          id: "",
          children: []
        }
      ],
      showDialog: false,
      storeInfo: {},
      defaultProps: { children: "children", label: "label" }
    };
  },
  mounted() {
    // ✅ 动态加载 AMap SDK
    this.loadAMapScript()
        .then(() => {
          // SDK 加载成功后再初始化
          this.$api.assignGetMapStoreVo({ brandPartyId: "" }).then(res => {
            this.initMap(res);
          });

          this.$api.assignGetBrandPartyVo().then(res => {
            res.map(a => {
              a.label = a.brandPartyName;
              a.id = a.id;
            });
            res.unshift({ label: "全部", id: "" });
            this.dataTree[0].children = res;
          });
        })
        .catch(err => {
          console.error(err);
          this.$message.error("高德地图加载失败，请检查网络或Key配置");
        });
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
      this.map = null;
    }
  },
  methods: {
    loadAMapScript() {
      return new Promise((resolve, reject) => {
        if (window.AMap) {
          return resolve(window.AMap);
        }
        const script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "https://webapi.amap.com/maps?v=2.0&key=b82250dbcb133271badaf05bab13eb27";
        script.onload = () => resolve(window.AMap);
        script.onerror = () => reject(new Error("AMap 加载失败"));
        document.head.appendChild(script);
      });
    },

    handleNodeClick(data) {
      console.log(data);
      this.$api.assignGetMapStoreVo({ brandPartyId: data.id }).then(res => {
        if (res.length === 0) {
          this.$message.success("该品牌方暂无门店列表！");
        }
        this.initMap(res);
      });
    },

    formatSerialNumber(val) {
      if (!val) return [];
      if (typeof val === "string") {
        return val.split(",").map(s => s.trim()).filter(Boolean);
      }
      if (Array.isArray(val)) return val;
      return [val];
    },

    renderContent(h, { data }) {
      const isImg =
          data.icon &&
          (data.icon.startsWith("http") ||
              data.icon.endsWith(".png") ||
              data.icon.endsWith(".jpg") ||
              data.icon.endsWith(".svg"));
      return h("span", { class: "custom-tree-node" }, [
        isImg
            ? h("img", {
              attrs: { src: data.icon, width: "16", height: "16" },
              style: { marginRight: "6px" }
            })
            : h("i", { class: data.icon, style: { marginRight: "6px" } }),
        h("span", data.label)
      ]);
    },

    _open(item) {
      this.$api.firmCameraGetLiveAddress({ serialNumber: item, type: 1 }).then(res => {
        this.$refs.cctv.init(res, item);
      });
    },

    initMap(res) {
      if (!window.AMap) {
        console.error("AMap 未加载成功");
        return;
      }

      // 销毁旧地图
      if (this.map) {
        this.map.destroy();
      }

      // ✅ 创建地图
      this.map = new AMap.Map("container", {
        resizeEnable: true,
        center: [112.98, 28.19],
        zoom: 10,
      });

      // 加载控件：比例尺 + 工具条 + 地图类型切换
      AMap.plugin(["AMap.Scale", "AMap.ToolBar", "AMap.MapType"], () => {
        const scale = new AMap.Scale(); // 比例尺
        const toolbar = new AMap.ToolBar(); // 工具条
        this.map.addControl(scale);
        this.map.addControl(toolbar);

        // 地图类型切换控件
        const mapType = new AMap.MapType({
          defaultType: 0, // 0为街道地图，1为卫星
          showRoad: true
        });
        this.map.addControl(mapType);
      });

      // 添加标记点
      const markers = res.map(el => {
        const lng = parseFloat(el.position[1]);
        const lat = parseFloat(el.position[0]);
        const icon = new AMap.Icon({
          image: "https://renovationcdn.jiachuangnet.com/icon.png",
          size: new AMap.Size(32, 32),
          imageSize: new AMap.Size(32, 32),
        });
        return new AMap.Marker({
          position: [lng, lat],
          icon,
          title: el.title,
          extData: { serialNumber: el.serialNumber, name: el.title },
        });
      });

      markers.forEach(marker => {
        this.map.add(marker);
        marker.on("click", () => {
          this.storeInfo = marker.getExtData();
          this.showDialog = true;
        });
      });
    },




  }
};
</script>

<style scoped lang="less">
::v-deep .el-tree .el-tree-node.is-current > .el-tree-node__content {
  height: 30px;
  background-color: rgba(26, 132, 232, 0.6);
  color: #ffffff;
  border-radius: 4px;
}

::v-deep .el-tree .el-tree-node__content:hover {
  background-color: rgba(255, 255, 255, 0.15);
  color: #fff;
  border-radius: 4px;
}

::v-deep .el-tree-node__content {
  height: 30px;
}
</style>
